package net.dybai.glacier;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {

    // 摘要算法
    private static final String ALGORITHM = "MD5";
    // 计算文件摘要时读取文件的缓存大小
    private static final int BUFSIZE = 1024 * 8;

    public static MessageDigest beginDigest() throws NoSuchAlgorithmException {
        return MessageDigest.getInstance(ALGORITHM);
    }

    public static void doDigest(MessageDigest messageDigest
            , byte[] data, int offset, int len) {
        messageDigest.update(data, offset, len);
    }

    public static byte[] endDigest(MessageDigest messageDigest) {
        return messageDigest.digest();
    }

    public static byte[] digest(String string) throws NoSuchAlgorithmException {
        byte[] data = string.getBytes(StandardCharsets.UTF_8);
        MessageDigest md = beginDigest();
        doDigest(md, data, 0, data.length);
        return endDigest(md);
    }

    public static byte[] digest(File file) throws NoSuchAlgorithmException
            , IOException {
        int readLen = -1;
        byte[] buf = new byte[BUFSIZE];

        if (!file.exists()) {
            throw new FileNotFoundException("File not found");
        }
        if (file.isDirectory()) {
            throw new IOException("It has to be a file");
        }

        try (InputStream in = new FileInputStream(file)) {
            MessageDigest md = beginDigest();
            while ((readLen = in.read(buf)) >= 0) {
                if (0 == readLen) continue;
                doDigest(md, buf, 0, readLen);
            }
            return endDigest(md);
        }
    }
}
